#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include "csapp.h"
#include <stdio.h>
using namespace std; 
//测试Malloc分配0字节的空间会产生什么样的结果； 
void testMalloc(){
	char *s = (char*) malloc(0); 
	if(s == NULL)
		cout << "NULL\n"; 
	else
		cout << "Not NULL\n"; 
}
//brk分配空间为堆上的空间； 
int* testBrk(){
	int *pInt = (int*)sbrk(4);
	*pInt = 1; 
	brk(pInt+1); 
	*(pInt+1)=2;
	return pInt; 
}
//创建空洞文件；

void createNull(){
	int fd = Open("test",O_CREAT|O_RDWR,DEF_MODE);
	int r = Write(fd,"hello",5); 
	Lseek(fd,10,SEEK_SET); 
	Write(fd,"nihao",5); 
	Close(fd);
	
}
void createBidFile(){
	int fd = Open("test",O_CREAT|O_WRONLY,DEF_MODE);
	int size ;
	cout << "请输入你需要创建的文件大小：(kb): "; 
	cin >> size ; 
	char buf[1024]; 
	memset(buf,65,1024);
	for(int i = 0; i <= size/1024 ; i++){
		rio_writen(fd,buf,1024);
	}
	Close(fd);
}
void testStrlen(){
	char *s="" ; 
	if(s == NULL)
		printf("NULL\n");
	printf("%d\n",strlen(s));
	printf("%x\n",s);
}
void isExist(){
	struct stat s; 
	int r = stat("fafa",NULL);
	if(r == -1)
		unix_error("错误:");
}
void testFormatWrite(){
	class Format{
	public:
		int num; 
		char name[10]; 
		char addr[10]; 
		int age; 
		Format(const int number,
				const char *n,
				const char *a,
				const int ages){
			num = number; 
			memcpy(name,n,10); 
			memcpy(addr,a,10); 
			age = ages; 
		}
		Format(){
			num = 0; 
			memcpy(name,"none",4);
			memcpy(addr,"none",4);
			age = 0; 
		}
	};
	FILE* file = NULL; 
	int r;
	file = fopen("./testFile.txt","w"); 
	if(file == NULL)
		unix_error("文件打开错误"); 
	Format format; 
	r = fwrite((void*)&format,sizeof(Format),1,file);
	if(r==-1)
		unix_error("写入第一次错误");
	format = Format(1001,"wang","ni",10); 
	fwrite((void*)&format,sizeof(Format),1,file);
	if(r==-1)
		unix_error("写入第二次错误");
	format = Format(1002,"leijie","hao",11);
	fwrite((void*)&format,sizeof(Format),1,file);
	if(r==-1)
		unix_error("写入第三次错误");
	fclose(file);
	file = fopen("./testFile.txt","r"); 
	if( file == NULL)
		unix_error("文件打开错误"); 
	r = fread((void*)&format,sizeof(Format),1,file);
	if(r == -1)
		unix_error("文件读入错误"); 
	r = fread((void*)&format,sizeof(Format),1,file);
	cout << "学号："<<format.num <<endl; 
	cout << "姓名：" << format.name <<endl; 
	cout << "住址：" << format.addr <<endl; 
	cout << "年龄：" << format.age <<endl; 
	

}
struct testStruct{
	char a[99]; 
	int b;
};
void testString(){
	string s=""; 
	s = s + "world"; 
	cout << s.size() <<endl; 
	cout << s.c_str() <<endl ;
	int fd = open("./shadow",O_RDONLY);
	cout<< fd <<endl; 
	close(fd);
}
void testParam(int a,int b){
	int c; 
}
#define OFFSET(stru,member) \
	((size_t)&(((stru*)0)->member))
int main(){
	//testMalloc(); 
	createNull();
	//testStrlen();
	//createBidFile();
	//isExist();
	/*chdir("/");
	char buf[100]={0}; 
	getcwd(buf,99); 
	system("pwd");
	printf("%s\n",buf);
	std::cout << getenv("PWD") << endl; 
	*/
	//testFormatWrite();
	//testString();
	cout << OFFSET(testStruct,b) <<endl;
	vector<int> vInt; 
}
